<!-- excel编辑 -->
<template>
  <div class="excel-edit-wp">
  	<div class="code-box">
  		<div class="btn-box">
  			<el-button @click="doExcelCode()">执行</el-button>
  			<el-button @click="doExport()">导出</el-button>
  			<el-button @click="doPrint()">打印</el-button>
  			<el-button @click="doCopy()">拷贝代码</el-button>
  			<el-button type="primary" @click="saveTemplate()">保存</el-button>
  		</div>
			<el-tabs class="code-tabs" v-model="_d.tabKey" type="card">
				<el-tab-pane v-for="(item, index) in _d.tabList" 
					:key="item.key" 
					:label="item.label" 
					:name="item.key"></el-tab-pane>
			</el-tabs>
			<div class="code-content">
				<div class="text t-header">{{currentTab.header}}</div>
				<div class="code-main" id="excelEditor"></div>
				<div class="text t-footer">{{currentTab.footer}}</div>
			</div>
  	</div>
  	<div class="preview-box">
  		<pdfPreview ref="previewRef" :config="previewConfig"></pdfPreview>
  	</div>
  </div>
</template>

<script setup>
	import { reactive, ref, watch, computed, onMounted } from 'vue'
	import {useRouter, useRoute} from "vue-router";
	import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
	import pdfPreview from "../preview/index.vue";
	import {ImportFile} from "/@/utils/Tools.js";
	import {$get, $post, $postparams} from '/@/utils/request';

	const router = useRouter();
	const route = useRoute();
	const previewRef = ref();

	const _d = reactive({
		id: '',
		record: null,

		data: '',
		tabKey: 'content',
		tabList: [
			{label: '内容', key: 'content', value: ''},
			{label: '初始化', key: 'onMounted', value: '', header: 'function (userInfo, route, request, ElMessage, Tools) {', footer: '}'},
			{label: '添加', key: 'add', value: ''},
			{label: '粘贴列表', key: 'copyTbody', value: '', header: 'function (ids, list, setValue) {', footer: '}'},
			{label: '改变', key: 'change', value: '', header: 'function (tool, request, ElMessage, Tools) {', footer: '}'},
			{label: '保存', key: 'save', value: '', header: 'function (request, ElMessage, Tools, oBox) {', footer: '}'},
		]
	})

	// 当前tab项
	const currentTab = computed(() => {
		return _d.tabList.find(item => item.key == _d.tabKey);
	})

	// 预览的配置
	const previewConfig = computed(() => {
		let obj = {};
		_d.tabList.forEach(item => {
			obj[item.key] = item.value;
		})
		return obj;
	})

	// 切换Tab
	watch(() => _d.tabKey, (val) => {
		let code = _d.tabList.find(item => item.key == val).value;
		oAce.setValue(code);
	})
	
	onMounted(() => {
		// 记录模板id
		_d.id = localStorage.getItem('template_id');

		oAce.init();

		let params = {
			input: _d.id
		}
		$get('/projectTemplateModule/getformtemplate', params).then(res => {
			if(!res.result.length) {
				return;
			}
			_d.record = res.result[0];
			// return;
			let content = _d.record.content || '';
			try{
				content = content ? JSON.parse(content) : [];
				_d.tabList.forEach(item => {
					// if(item.key == 'onMounted') {
					// 	item.value = '';
					// } else {
					// 	item.value = content[item.key] || '';
					// }
					item.value = content[item.key] || '';
				})

				oAce.setValue(_d.tabList.find(item => item.key == _d.tabKey).value);
			} catch(err) {
				console.log(err);
			}
		})

		// ImportFile('/FileTemplate/采购预算清单-预算明细.txt').then(res => {
		// 	_d.tabList.forEach(item => {
		// 		item.value = res[item.key] || '';
		// 	})

		// 	oAce.setValue(_d.tabList.find(item => item.key == _d.tabKey).value);
		// })

		// getData();
	})

	function getData() {
		_d.tabList[0].value = ` 
<thead>
	<tr>
		<td colspan="3" style="border: 1px solid #000; height: 50pt; font-size: 20pt; text-align: center; font-weight: bold;">大标题</td>
	</tr>
	<tr>
		<td style="border: 1px solid #000; width: 100pt; text-align: center; height: 40pt; font-weight: bold;">姓名</td>
		<td style="border: 1px solid #000; width: 100pt; text-align: center; height: 40pt; font-weight: bold;">科目</td>
		<td style="border: 1px solid #000; width: 100pt; text-align: center; height: 40pt; font-weight: bold;">成绩</td>
	</tr>
</thead>
<tbody>
	<tr>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;" rowspan="3">
			##json:
				{"type": "input", "label": "姓名", "key": "name", "value": "张三"}
			##
		</td>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">数学</td>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">
			##json:
				{"type": "inputNumber", "label": "成绩", "key": "score", "value": ""}
			##
		</td>
	</tr>
	<tr>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">语文</td>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">
			##json:
				{"type": "inputNumber", "label": "成绩", "key": "score", "value": ""}
			##
		</td>
	</tr>
	<tr>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">英语</td>
		<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">
			##json:
				{"type": "inputNumber", "label": "成绩", "key": "score", "value": ""}
			##
		</td>
	</tr>
</tbody>
<tfooter>
	<tr>
		<td style="width: 100pt; height: 20pt;"></td>
		<td style="width: 100pt; height: 20pt;"></td>
		<td style="width: 100pt; height: 20pt;">
			##json:
				{"type": "text", "value": "平均成绩：110"}
			##
		</td>
	</tr>
</tfooter>	
		`;
		_d.tabList[1].value = ` 
<tr>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;" rowspan="3">
		##json:
			{"type": "input", "label": "姓名", "key": "name", "value": ""}
		##
	</td>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">数学</td>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">
		##json:
			{"type": "inputNumber", "label": "成绩", "key": "score", "value": ""}
		##
	</td>
</tr>
<tr>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">语文</td>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">
		##json:
			{"type": "inputNumber", "label": "成绩", "key": "score", "value": ""}
		##
	</td>
</tr>
<tr>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">英语</td>
	<td style="border: 1px solid #000; width: 100pt; text-align:center; height: 30pt;">
		##json:
			{"type": "inputNumber", "label": "成绩", "key": "score", "value": ""}
		##
	</td>
</tr>
		`;
		_d.tabList[2].value = ` 
let aTr = oTbody.querySelectorAll('tr');
if(aTr.length <= 3) {
	ElMessage.error('不能更少了')
	return false;
}
for(let i = aTr.length-1; i >= aTr.length-3; i--) {
	oTbody.removeChild(aTr[i]);
}
return true; 		
		`;
		_d.tabList[3].value = ` 
outfor:for(let i = 0; i < tableTools.length; i++) {
	for(let j = 0; j < tableTools[i].length; j++) {
		let obj = tableTools[i][j];
		console.log(obj);
		if(obj.key == 'score') {
			break outfor;
		}
	}
}		
		`;
		_d.tabList[4].value = ` 
for(let i = 0; i < tableTools.length; i++) {
	let aItem = tableTools[i];
	for(let j = 0; j < aItem.length; j++) {
		let bItem = aItem[j];
		if(typeof bItem.value == 'string' && !bItem.value.length) {
			ElMessage.error(bItem.label+'不能为空');
			return;
		}
	}
}
console.log(tableTools);
		`;

		oAce.setValue(_d.tabList.find(item => item.key == _d.tabKey).value);
	}

	// 执行excel代码
	function doExcelCode() {
		let data = oAce.getValue();
		let oTab = _d.tabList.find(item => item.key == _d.tabKey);
		oTab.value = data;
	}

	// 导出
	function doExport() {
		previewRef.value.export();
	}

	// 打印
	function doPrint() {
		previewRef.value.print();
	}

	// 拷贝
	function doCopy() {
		previewRef.value.copy();
	}

	// 保存
	function saveTemplate() {
		// console.log(previewRef.value.getCode());return;
		ElMessageBox.confirm('此操作将保存该模板，是否继续？', '提示', {
			type: 'warning'
		}).then(async () => {
			let params = {
				formTemplate: {
					id: _d.record.id,
					content: await previewRef.value.getCode()
				}
			}
			$post('/projectTemplateModule/modifyformtemplate', params).then(res => {
				ElNotification({
			    title: '提示',
			    message: '编辑成功',
			    type: 'success',
			  })
			  router.back();
			})
		})
	}

	// 编辑
  const oAce = {
    editor: null,
    timer: null,
    code: '',
    // 初始化Ace
    async init () {
      this.editor = ace.edit('excelEditor');
      // this.editor.session.setMode('ace/mode/javascript'); // 设置语言
      this.editor.setTheme('ace/theme/tomorrow'); // 设置主题
      this.editor.setOptions({
      	tabSize: 2,
        enableBasicAutocompletion: true,
        enableSnippets: true,
        // enableLiveAutocompletion: true// 设置自动提示
      })
    },
    // 设置ace-editor内容文本
    setValue (code) {
    	this.editor.setValue(code, -1);
    },
    getValue () {
      return this.editor.getValue();
    }
  }
</script>

<style lang="scss" scoped>
.excel-edit-wp {
	padding: 5px;
	.code-box {
		position: relative;
		height: 300px;
		width: 100%;
		border: 1px solid #dfdfdf;
		background: #fff;
		display: flex;
		flex-direction: column;
		.btn-box {
			position: absolute;
			right: 10px;
			top: 8px;
			z-index: 2;
		}
		.code-tabs {
			:deep(.el-tabs__header) {
				margin-bottom: 0;
			}
		}
		.code-content {
			flex: 1;
			height: 0;
			display: flex;
			flex-direction: column;
			.text {
				padding-left: 18px;
				height: 18px;
				line-height: 18px;
				background: #F4F4F5;
				color: #999;
				font-size: 14px;
				font-family: Courier New;
			}
			.code-main {
				flex: 1;
				height: 0;
			}
		}
	}
	.preview-box {
		flex: 1;
		height: 0;
		width: 100%;
		border: 1px solid #dfdfdf;
		border-top: none;
		background: #fff;
		overflow: auto;
	}
}
</style>